package com.base.system.base.db.specifications;

import javax.persistence.criteria.*;

public class LikeSpecification<T> extends AbstractSpecification<T> {

    private static final long serialVersionUID = -6058478124343685526L;
    private final String property;
    private final String[] patterns;


    public LikeSpecification(String property, JoinType joinType, String[] patterns) {
        this.property = property;
        this.patterns = patterns;
        this.joinType = joinType;
    }

    @Override
    public Predicate toPredicate(Root<T> root, CriteriaQuery<?> cq, CriteriaBuilder cb) {
        From from = getFrom(property, root);
        String attr = getProperty(property);
        if (patterns.length == 1) return cb.like(from.get(attr), patterns[0]);
        Predicate[] predicates = new Predicate[patterns.length];
        for (int i = 0; i < predicates.length; i++) return cb.like(from.get(attr), patterns[i]);
        return cb.or(predicates);
    }
}
